package com.chao.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chao.entity.Teacher;
import com.chao.service.impl.TeacherServiceImpl;
import com.chao.utils.TypeConversion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Controller
public class TeacherController {

    @Autowired
    TeacherServiceImpl teacherService;


    // 数据更新
    @PutMapping("updateTeacher")
    public String teacher_update(Teacher teacher,
                                 @RequestParam(defaultValue = "1") Integer pn,
                                 RedirectAttributes ra) {
        teacherService.getBaseMapper().updateById(teacher);
        ra.addAttribute("pn", pn);
        return "redirect:/teacher_table";
    }


    // 删除 数据
    @GetMapping("/deleteTeacher/{tIds}")
    public String teacher_delete(@PathVariable String tIds,
                                 @RequestParam(defaultValue = "1") Integer pn,
                                 RedirectAttributes ra) {
        if(tIds.contains("-")) {
            String[] strings = tIds.split("-");
            List<Integer> integers = TypeConversion.strArrToIntegerList(strings);
            teacherService.removeByIds(integers);
        } else {
            teacherService.removeById(Integer.parseInt(tIds));
        }
        ra.addAttribute("pn", pn);
        return "redirect:/teacher_table";
    }


    // 添加数据
    @PostMapping("/teacher")
    public String teacher_add(@Valid Teacher teacher,
                              @RequestParam(defaultValue = "1") Integer pn,
                              RedirectAttributes ra) {
        teacher.setTDate(new Date());
        teacherService.addOfPrimary(teacher);
        ra.addAttribute("pn", pn);
        return "redirect:/teacher_table";
    }

    @GetMapping("/teacher_table")
    public String teacher_table(@RequestParam(defaultValue = "1") Integer pn,
                                Model model) {
        Page<Teacher> page = new Page<>(pn, 5);
        Page<Teacher> teacherPage = teacherService.page(page);
        List<Teacher> teachers = teacherPage.getRecords();
        model.addAttribute("page", page);
        model.addAttribute("teachers", teachers);
        return "teacher/teacher_table";
    }

}
